package com.ruoyi.cms.fileinfo.controller;

import com.ruoyi.cms.fileinfo.domain.FilePostInfo;
import com.ruoyi.cms.fileinfo.domain.SysFileInfo;
import com.ruoyi.cms.fileinfo.service.IFilePostInfoService;
import com.ruoyi.cms.fileinfo.service.ISysFileInfoService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author toumakazusa
 * @since 1.0.0
 */
@RestController
@RequestMapping("/filePostInfo")
@Api("帖子关联文件管理")
public class FilePostInfoController extends BaseController {

    @Autowired
    private IFilePostInfoService filePostInfoService;

    @Autowired
    private ISysFileInfoService fileInfoService;


    /**
     * 删除post文件关联
     */
    @PreAuthorize("@ss.hasPermi('cms:post:remove')")
    @DeleteMapping("/{postIds}")
    @ApiOperation("删除post文件关联")
    public AjaxResult remove(@PathVariable Long[] postIds) {
        for (Long id : postIds) {
            List<FilePostInfo> filePostInfos = filePostInfoService.selectFilePostList(id);
            filePostInfos.forEach((FilePostInfo filePostInfo) -> {
                Long fileId = filePostInfo.getFileId();
                fileInfoService.deleteSysFileInfoByFileId(fileId);
            });
        }
        filePostInfoService.deleteFilePost(postIds);
        return toAjax(1);
    }


    /**
     * 根据postId获取文件列表
     */
    @PreAuthorize("@ss.hasPermi('cms:post:query')")
    @GetMapping(value = "/{postId}")
    public AjaxResult getInfo(@PathVariable Long postId) {
        List<SysFileInfo> sysFileInfoList = new ArrayList<>();
        List<FilePostInfo> filePostInfos = filePostInfoService.selectFilePostList(postId);
        filePostInfos.forEach((FilePostInfo filePostInfo) -> {
            Long fileId = filePostInfo.getFileId();
            SysFileInfo sysFileInfo = fileInfoService.selectSysFileInfoByFileId(fileId);
            if (sysFileInfo != null) {
                sysFileInfoList.add(sysFileInfo);
            }
        });
        return AjaxResult.success(sysFileInfoList);
    }

}
